<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div id="app"></div>

    <script type="module">
      import { createApp } from "./lib/vue3.esm.browser.js";

      const app = createApp({
        template: `
        <div style="display: flex">
          <div>
            <h2>书籍列表</h2>
            <FancyList apiUrl="http://localhost:3000/books" search>
              <template v-slot:default="scopeProps">
                <div>书名：{{ scopeProps.title }}</div>
              </template>
            </FancyList>
          </div>

          <div>
            <h2>待办列表</h2>
            <FancyList apiUrl="http://localhost:3000/todos" search>
              <template v-slot:default="scopeProps">
                <label>
                  <input type="checkbox" />
                  <span>{{ scopeProps.name }}</span>
                </label>
              </template>
            </FancyList>
          </div>
        </div>
        `,
      });

      /**
       * 通用的列表组件
       *
       */
      app.component("FancyList", {
        template: `
          <form v-if="search" @submit.prevent="handleSubmit">
            <input ref="keyword" type="search" />  
          </form>

          <ul>
            <li v-for="item in list" :key="item.id">
              <slot v-bind="item" />  
            </li>  
          </ul>
        `,

        props: {
          // 请求地址
          apiUrl: {
            type: String,
            required: true,
          },
          // 是否需要搜索功能
          search: {
            type: Boolean,
            default: false,
          },
        },

        data() {
          return {
            list: [],
          };
        },

        methods: {
          refresh(keyword) {
            let url = this.apiUrl;
            // 根据是否有 keyword 来拼接请求参数
            if (keyword) {
              url += "?q=" + keyword;
            }

            fetch(url)
              .then((response) => response.json())
              .then((result) => {
                this.list = result;
              });
          },

          // 搜索功能
          handleSubmit(event) {
            // 1. 获取搜索关键字
            const keyword = this.$refs.keyword.value;

            // 2. 重新刷新数据
            this.refresh(keyword);

            console.log("handleSubmit", keyword);
          },
        },

        created() {
          this.refresh();
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
